<template>
  <view class="container">
    <view class="video-container">
      <video
        v-if="videoSrc"
        :src="videoSrc"
        :controls="true"
        :autoplay="false"
        :show-fullscreen-btn="true"
        :show-play-btn="true"
        :enable-progress-gesture="true"
        :enable-play-gesture="true"
        style="width: 100%; height: 420rpx;"
        @fullscreenchange="onFullScreenChange"
        @touchstart="onTouchStart"
        @touchmove="onTouchMove"
        @touchend="onTouchEnd"
      ></video>
    </view>
    <view class="video-title">
      {{ videoTitle }}
    </view>
  </view>
</template>

<script setup>
const videoSrc = ref('')
const videoTitle = ref('')
const isFullScreen = ref(false)
const touchStartY = ref(0)
const currentVideoIndex = ref(0)
const videoList = ref([])

// 从全局获取视频列表和当前索引
onLoad((options) => {
  if (options.src) {
    videoSrc.value = decodeURIComponent(options.src)
  }
  if (options.title) {
    videoTitle.value = decodeURIComponent(options.title)
  }
  
  // 从全局获取视频列表数据
  const globalData = getApp().globalData
  if (globalData && globalData.videoList) {
    videoList.value = globalData.videoList
    // 查找当前视频在列表中的位置
    currentVideoIndex.value = videoList.value.findIndex(video => 
      video.videoSourceId === videoSrc.value
    )
  }
})

const onFullScreenChange = (e) => {
  isFullScreen.value = e.detail.fullScreen
}

const onTouchStart = (e) => {
  if (!isFullScreen.value) return
  touchStartY.value = e.touches[0].clientY
}

const onTouchMove = (e) => {
  // 在全屏模式下处理滑动
}

const onTouchEnd = (e) => {
  if (!isFullScreen.value || !videoList.value.length) return
  
  const touchEndY = e.changedTouches[0].clientY
  const deltaY = touchEndY - touchStartY.value
  
  // 判断滑动方向和距离
  if (Math.abs(deltaY) > 50) { // 滑动距离需大于50像素才触发
    if (deltaY > 0) {
      // 向下滑动，播放上一个视频
      playPreviousVideo()
    } else {
      // 向上滑动，播放下一个视频
      playNextVideo()
    }
  }
}

const playNextVideo = () => {
  if (currentVideoIndex.value < videoList.value.length - 1) {
    currentVideoIndex.value++
    const nextVideo = videoList.value[currentVideoIndex.value]
    videoSrc.value = nextVideo.videoSourceId
    videoTitle.value = nextVideo.title
  }
}

const playPreviousVideo = () => {
  if (currentVideoIndex.value > 0) {
    currentVideoIndex.value--
    const prevVideo = videoList.value[currentVideoIndex.value]
    videoSrc.value = prevVideo.videoSourceId
    videoTitle.value = prevVideo.title
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.video-container {
  margin-bottom: 30rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.video-title {
  font-size: 32rpx;
  font-weight: bold;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}
</style>